package com.yimi.yinhepda.db.dao;

import android.database.sqlite.SQLiteDatabase;

import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.Where;
import com.j256.ormlite.support.DatabaseConnection;
import com.yimi.yinhepda.base.BaseApplication;
import com.yimi.yinhepda.db.helper.DbHelper;
import com.yimi.yinhepda.db.table.StorageDetailTable;
import com.yimi.yinhepda.db.table.StorageInfoTable;
import com.yimi.yinhepda.entity.response.StorageInfo;
import com.pda.uce.commom.util.LogUtil;

import java.sql.SQLException;
import java.util.List;

/**
 * @author 000432
 * 库区基础资料数据操作
 */
public class StorageInfoTableDao extends BaseDao<StorageInfoTable, Long> {

    public StorageInfoTableDao() {
        super(DbHelper.getInstance(BaseApplication.getContext()), StorageInfoTable.class);
    }

    public List<StorageInfoTable> findDeptCode(String deptCode, String nextCode) {
        try {
            QueryBuilder<StorageInfoTable, Long> queryBuilder = dao.queryBuilder();
            Where where = queryBuilder.where();
            where.eq("deptCode", deptCode);
            where.and().eq("nextCode", nextCode);
            return queryBuilder.query();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public String findOrderByLatestTime() {
        String lastTime = null;
        try {
            QueryBuilder<StorageInfoTable, Long> queryBuilder = dao.queryBuilder().orderBy("lastTime", false).limit(1L);
            List<StorageInfoTable> list = queryBuilder.query();
            if (list != null && list.size() > 0) {
                lastTime = list.get(0).getLastTime();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return lastTime;
    }

    /**
     * 只查询latestTime字段的最新时间，可提高查询速度
     */
    public String findOrderByLatestTime2() {
        String lastTime = null;
        try {
            QueryBuilder<StorageInfoTable, Long> queryBuilder = dao.queryBuilder();
            queryBuilder.selectColumns("lastTime");
            queryBuilder.orderBy("lastTime", false).limit(1L);
            List<StorageInfoTable> list = queryBuilder.query();
            if (list != null && list.size() > 0) {
                lastTime = list.get(0).getLastTime();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return lastTime;
    }

    public void createOrUpdate(List<StorageInfo> list) {
        SQLiteDatabase database = getDbHelper().getWritableDatabase();
        String tableName = dao.getTableName();
        StringBuilder sql = new StringBuilder("replace into ");
        sql.append(tableName);
        sql.append("(storageId,");
        sql.append("storageType,");
        sql.append("storageCode,");
        sql.append("deptCode,");
        sql.append("storageName,");
        sql.append("placeName,");
        sql.append("remark,");
        sql.append("compCode,");
        sql.append("creater,");
        sql.append("createrTime,");
        sql.append("modifier,");
        sql.append("modifierTime,");
        sql.append("isDelete,");
        sql.append("recordVersion,");
        sql.append("nextCode,");
        sql.append("lastTime)");
        //16
        sql.append("values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
        LogUtil.e("sql=" + sql.toString());

        database.beginTransaction();
        for (StorageInfo item : list) {
            Object[] values = new Object[]{
                    item.getStorage_id(), item.getStorage_type(), item.getStorage_code(), item.getDept_code(), item.getStorage_name(), item.getPlace_name(),
                    item.getRemark(), item.getComp_code(), item.getCreater(), item.getCreater_time(), item.getModifier(), item.getModifier_time(),
                    item.getIs_delete(), item.getRecord_version(), "", item.getLatest_time()
            };
            database.execSQL(sql.toString(), values);
        }
        database.setTransactionSuccessful();
        database.endTransaction();
    }

    /**
     * 根据库存详细信息修改数据
     */
    public void updateByStorageDetail(List<StorageDetailTable> list) {
        DatabaseConnection databaseConnection = null;
        try {
            try {
                databaseConnection = dao.startThreadConnection();
                dao.setAutoCommit(databaseConnection, false);
                for (StorageDetailTable item : list) {
                    if (item.getIsDelete() == 0) {
                        String storageCode = item.getStorageCode();
                        StorageInfoTable storageInfo = findByStorageCode(storageCode);
                        if (storageInfo != null) {
                            storageInfo.setNextCode(item.getNextCode());
                            try {
                                dao.update(storageInfo);
                            } catch (SQLException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
                dao.commit(databaseConnection);
            } catch (SQLException e) {
                dao.rollBack(databaseConnection);
                e.printStackTrace();
            } finally {
                dao.endThreadConnection(databaseConnection);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新库区信息，从库区明细中获取下一站code.
     */
    public void updateByStorageDetail2() {
        DatabaseConnection databaseConnection = null;
        try {
            List<StorageInfoTable> list = findAll();
            StorageDetailTableDao storageDetailTableDao = new StorageDetailTableDao();
            databaseConnection = dao.startThreadConnection();
            dao.setAutoCommit(databaseConnection, false);
            for (StorageInfoTable item : list) {
                if (item.getIsDelete() == 0 && (item.getNextCode() == null || item.getNextCode().equals(""))) {
                    String storageCode = item.getStorageCode();
                    StorageDetailTable storageInfo = storageDetailTableDao.findByStorageCode(storageCode);
                    if (storageInfo != null) {
                        item.setNextCode(storageInfo.getNextCode());
                        try {
                            dao.update(item);
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            dao.commit(databaseConnection);
        } catch (SQLException e) {
            try {
                dao.rollBack(databaseConnection);
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            try {
                dao.endThreadConnection(databaseConnection);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 根据库区编码查询
     */
    public StorageInfoTable findByStorageCode(String storageCode) {
        try {
            QueryBuilder<StorageInfoTable, Long> queryBuilder = dao.queryBuilder().limit(1L);
            Where where = queryBuilder.where();
            where.eq("storageCode", storageCode);
            List<StorageInfoTable> list = queryBuilder.query();
            if (list != null && list.size() > 0) {
                return list.get(0);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查询库区名称
     */
    public StorageInfoTable findStorageNameInfo(String compCode, String deptCode, String storageCode) {
        try {
            QueryBuilder<StorageInfoTable, Long> queryBuilder = dao.queryBuilder().limit(1L);
            Where where = queryBuilder.where();
            where.eq("isDelete", 0);
            where.and().eq("compCode", compCode);
            where.and().eq("deptCode", deptCode);
            where.and().eq("storageCode", storageCode);
            List<StorageInfoTable> list = queryBuilder.query();
            if (list != null && list.size() > 0) {
                return list.get(0);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查询库区名称
     */
    public List<StorageInfoTable> queryStorageInfos(String compCode, String deptCode) {
        try {
            QueryBuilder<StorageInfoTable, Long> queryBuilder = dao.queryBuilder();
            Where where = queryBuilder.where();
            where.eq("isDelete", 0);
            where.and().eq("compCode", compCode);
            where.and().eq("deptCode", deptCode);
            return queryBuilder.query();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据部门code和库区code查询库区名称
     */
    public StorageInfoTable findStorageName(String deptCode, String storageCode) {
        try {
            QueryBuilder<StorageInfoTable, Long> queryBuilder = dao.queryBuilder();
            Where where = queryBuilder.where();
            where.eq("isDelete", 0);
            where.and().eq("deptCode", deptCode);
            where.and().eq("storageCode", storageCode);
            return queryBuilder.queryForFirst();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据部门code查询库区
     */
    public List<StorageInfoTable> findAreaCodes(String deptCode) {
        try {
            QueryBuilder<StorageInfoTable, Long> queryBuilder = dao.queryBuilder();
            Where where = queryBuilder.where();
            where.eq("isDelete", 0);
            where.and().eq("deptCode", deptCode);
            return queryBuilder.query();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
